package com.zhaofan.other;

import org.junit.Test;

/**
 * 14. 最长公共前缀
 * https://leetcode-cn.com/problems/longest-common-prefix/
 */
public class No14 {

    @Test
    public void test(){
        String[] s={"flower","flow","flight"};
        System.out.println(longestCommonPrefix(s));
    }

    public String longestCommonPrefix(String[] strs) {
        if(strs==null||strs.length==0){
            return "";
        }else if(strs.length==1){
            return strs[0];
        }

        String s=strs[0].length()>strs[1].length()?strs[0].substring(0,strs[1].length()):strs[0];//避免strs[1]比strs[0]短的情况
        for(int i=1;i<strs.length;++i){
            String s1=strs[i];
            s=s.length()>s1.length()?s.substring(0,s1.length()):s;

            for(int j=0;j<s.length()&&j<s1.length();++j){
                if(s1.charAt(j)!=s.charAt(j)){
                    s=s.substring(0,j);
                    break;
                }
            }
        }
        return s;
    }
}
